﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace psafth.Common.Extensions
{
    public static class IEnumerableExtensions
    {
        public static List<IEnumerable<T>> Split<T>(this IEnumerable<T> arrayToSplit, T splitter, bool removeEmpty = true)
        {
            List<IEnumerable<T>> splittedList = new List<IEnumerable<T>>();

            int handled = 0;

            while (handled < arrayToSplit.Count())
            {
                IEnumerable<T> result = arrayToSplit.Skip(handled).TakeWhile(obj => !obj.Equals(splitter));
                result = result.Add<T>(splitter);

                handled += result.Count();

                if (result.Count() > 0 || result.Count() == 0 && !removeEmpty)
                    splittedList.Add(result);
            }

            return splittedList;
        }

        public static IEnumerable<T> Add<T>(this IEnumerable<T> source, T additionalItem)
        {
            foreach (var item in source)
            {
                yield return item;
            }

            yield return additionalItem;
        }
    }
}
